/*
 * @Author: Tommy Chen weiyao_85@163.com
 * @Date: 2024-05-08 09:53:39
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-05-11
 * @FilePath: /macc.admin.vue/src/project/authSys/router/async.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import VueRouter from 'vue-router';
import router from './index';
import { defaultRoutes } from '@projectCommon/router/routers';
import { selfRoutes } from '../router/selfRouter';

let _import = (view) => {
  //解决vue 路由懒加载，webpack 处理import时，import中无法解析纯变量的路径，需要传字符串+变量的方式
  if (view.includes('authSys/')) {
    return () => import(`@project/${view}`);
  } else {
    return () => import(`@views/${view}`);
  }
};

export const getAsyncRoutes = (routeArr) => {
  const accessedRouters = routeArr.filter((route) => {
    if (route.component) {
      route.component = _import(route.component);
    }

    if (route.children && route.children.length) {
      route.children = getAsyncRoutes(route.children);
    }
    return true;
  });

  return accessedRouters;
};

export const setAsyncRoutes = (menu) => {
  const _menu = getAsyncRoutes(menu);
  // 将处理好的动态配置的路由通过 vue 提供的方式添加到 router 中，注意这个 _menu 的格式是和配置路由时的键 routes 一样格式的数组
  const authRouter = {
    path: '/',
    // name: 'Main',
    component: () => import('@project/authSys/views/Main.vue'),
    redirect: () => {
      console.log(_menu);
      if (window == window.top) {
        const indexRouter = _menu.find((item) => item.name === 'Index');
        return indexRouter.path;
      } else {
        return '/';
      }
    },
    meta: {
      requireAuth: true,
    },
    children: [..._menu, ...selfRoutes],
  };
  console.log('router.options', router.options);

  router.addRoute(authRouter);

  const page404 = {
    // 404配置 (404要放最后，否则会被优先匹配到)
    path: '*',
    name: 'unFindPage',
    component: () => import('@/views/404.vue'),
  };
  router.addRoute(page404);

  // 路由 options 并不会随着 addRoutes 动态响应，所以要在这里进行设置
  router.options.routes = defaultRoutes.concat(_menu, page404);
};

//更新路由
export const updateAsyncRoutes = (menu) => {
  const newRouter = new VueRouter({
    routes: defaultRoutes,
  });
  router.matcher = newRouter.matcher;
  setAsyncRoutes(menu);
};
